package com.supermarket.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.supermarket.dto.OrderPageQueryDto;
import com.supermarket.entity.Order;
import com.supermarket.exception.BusinessException;
import com.supermarket.mapper.OrderMapper;
import com.supermarket.service.OrderService;
import com.supermarket.utils.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 分页查询订单列表
     */
    @Override
    public PageResult list(OrderPageQueryDto orderPageQueryDto) {
        PageHelper.startPage(orderPageQueryDto.getPage(), orderPageQueryDto.getPageSize());
        Page<Order> page = (Page<Order>) orderMapper.list(orderPageQueryDto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询订单
     */
    @Override
    public Order getById(Long id) {
        Order order = orderMapper.getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        return order;
    }

    /**
     * 更新订单状态
     */
    @Override
    @Transactional
    public void update(Long id, Integer status) {
        Order order = getById(id);

        // 检查状态转换是否合法
        if (!isValidStatusTransition(order.getStatus(), status)) {
            throw new BusinessException("非法的状态转换");
        }

        // 更新订单状态
        orderMapper.updateStatusById(id, status);
    }

    /**
     * 删除订单
     */
    @Override
    @Transactional
    public void delete(Long id) {
        Order order = getById(id);

        // 只有已取消的订单才能删除
        if (order.getStatus() != 4) {
            throw new BusinessException("只能删除已取消的订单");
        }

        orderMapper.deleteById(id);
    }

    /**
     * 检查订单状态转换是否合法
     */
    private boolean isValidStatusTransition(Integer currentStatus, Integer newStatus) {
        // 订单状态：0-待付款 1-待发货 2-已发货 3-已完成 4-已取消
        switch (currentStatus) {
            case 0: // 待付款
                return newStatus == 1 || newStatus == 4; // 可以付款或取消
            case 1: // 待发货
                return newStatus == 2; // 可以发货
            case 2: // 已发货
                return newStatus == 3; // 可以确认收货
            default:
                return false; // 其他状态不能改变
        }
    }
}
